package com.demo.goods.web;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.demo.goods.config.PatternProperties;
import com.demo.goods.pojo.User;
import com.demo.goods.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PatternProperties patternProperties;

    @SentinelResource(value = "getInfo", blockHandler = "blockHandler", fallback = "fallback" )
    @GetMapping("/{id}")
    public User getInfo(@PathVariable("id") Long id) {
        System.out.println(patternProperties.getPageSize());
        // 模拟异常熔断
//        int flag = 10 / 0;
        return userService.getById(id);
    }
    /**
     * 限流触发的方法
     * 注意：限流返回值必须与接口返回值类型一致，参数必须与接口传参方法一致
     */
    public User blockHandler(@PathVariable("id") Long id, BlockException e) {
        System.out.println(e);
        return new User().setName("哈哈哈，你用户点太快了,被限流了吧！！！");
    }
    /**
     * 熔断触发的方法
     * 注意：熔断返回值必须与接口返回值类型一致，参数必须与接口传参方法一致
     */
    public User fallback(@PathVariable("id") Long id) {
        return new User().setName("哈哈哈，这用户是一个熔断降级方法哦！！！");
    }
    @GetMapping("/list")
    public List<User> list() {
        return userService.list().stream().limit(Long.valueOf(patternProperties.getPageSize())).collect(Collectors.toList());
    }

    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        if (userService.save(user)) {
            response.put("code", 200);
            response.put("msg", "添加成功");
        } else {
            response.put("code", 500);
            response.put("msg", "添加失败");
        }
        return response;
    }

    @PutMapping("/update")
    public Map<String, Object> edit(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        if (userService.updateById(user)) {
            response.put("code", 200);
            response.put("msg", "修改成功");
        } else {
            response.put("code", 500);
            response.put("msg", "修改失败");
        }
        return response;
    }


    @DeleteMapping("/{id}")
    public Map<String, Object>  remove(@PathVariable("id") Long id) {
        Map<String, Object> response = new HashMap<>();
        if (userService.removeById(id)) {
            response.put("code", 200);
            response.put("msg", "删除成功");
        } else {
            response.put("code", 500);
            response.put("msg", "删除失败");
        }
        return response;
    }
}
